package com.sky.controller.user;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.properties.WeChatProperties;
import com.sky.service.OrderService;
import com.sky.websocket.WebSocketServer;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * 支付回调相关接口
 */
@RestController
@RequestMapping("/notify")
@Slf4j
public class PayNotifyController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 支付成功回调
     *
     * @param request
     */
    @RequestMapping("/paySuccess")
    public void paySuccessNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("支付成功回调数据：{}", request);
        //读取数据
        String body = readData(request);
        // {"id":"0c4eeb12-cc9d-5af3-93ff-700d6d15a5bf","create_time":"2025-03-13T14:31:53+08:00","resource_type":"encrypt-resource","event_type":"TRANSACTION.SUCCESS","summary":"支付成功","resource":{"original_type":"transaction","algorithm":"AEAD_AES_256_GCM","ciphertext":"GRvbd3/Iwcc/dtQqQtMrGVLxeEwlNhj+eGmHfmACqkaPAJgUoQ7V1DV/Z2p36gH2/7VGaDzWqbAuu43M2EPjn8Usti8BBYBNWwpb82bSwWjNqBWWisvfAWyMIvS1SuI5d6tR1Jdt99fbqvX+Nuq1Nf4rvajDNwarS+TzpSqmxD8+gL/WWkz13zxGI/L7GrErhVZJb7mukZl0qpVI7+Xa8Mh0I4r8A3xHp3ugHVpIicztV1JlKl0RQqV5QK5asr75faVzTNjlr9vjCCxm22cibt1FFesW8JoJJMGGwZH0Jf9AGMvxq6DPUx1ATfNz+gzEhDxD20xXqSzqc0mVEoS/dCEU3rwblv1TB1qW8F6HxMA/QmU40yGFZvQDc2Z3ZzQx51J71tgKn9YBCK2AJKl3ds/ag+SWz6TYzoK2tdr366/eu1OiKelRucu+oxodJnhoYTnUf4lZvsG1zx0+iZRwAYQzLEk1vBMIwCBgRCTpfLQf6KvIgdKhVY6cdH7WnSa+vL8GRGawjg2Toy9QQoBLSZXLCgz/EAlfOtUmvG1vDM7CQKBsab0OVlpn5mc97cc=","associated_data":"transaction","nonce":"s3OMK4fOsXON"}}
        log.info("支付成功回调：{}", body);

        //数据解密
        String plainText = decryptData(body);
        // {"mchid":"1537915151","appid":"wxa512dc32605ae94f","out_trade_no":"1741847477974","transaction_id":"4200002710202503130484222134","trade_type":"JSAPI","trade_state":"SUCCESS","trade_state_desc":"支付成功","bank_type":"BOC_DEBIT","attach":"","success_time":"2025-03-13T14:31:53+08:00","payer":{"openid":"oKWCL7Q2WqWpMqK0vd5syBpe2Q80"},"amount":{"total":1,"payer_total":1,"currency":"CNY","payer_currency":"CNY"}}
        log.info("解密后的文本：{}", plainText);

        JSONObject jsonObject = JSON.parseObject(plainText);
        String outTradeNo = jsonObject.getString("out_trade_no");//商户平台订单号
        String transactionId = jsonObject.getString("transaction_id");//微信支付交易号
        log.info("商户平台订单号：{}", outTradeNo);
        log.info("微信支付交易号：{}", transactionId);
        if (jsonObject.getString("trade_state").equals("SUCCESS")) {
            log.info("支付成功");
            //业务处理，修改订单状态、来单提醒
            orderService.paySuccess(outTradeNo);
            // 来单提醒
            log.info("来单提醒");
            // 组装发送给客户端约定的消息内容
            JSONObject messageObj = new JSONObject();
            messageObj.put("orderId", outTradeNo); // 订单号
            messageObj.put("type", "1"); // 1代表来单提醒
            messageObj.put("content", "新订单:" + outTradeNo); // 内容
            webSocketServer.sendToAllClient(messageObj.toJSONString());
            //给微信响应
            responseToWeixin(response);
        }
    }

    /**
     * 读取数据
     *
     * @param request
     * @return
     * @throws Exception
     */
    private String readData(HttpServletRequest request) throws Exception {
        BufferedReader reader = request.getReader();
        StringBuilder result = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (result.length() > 0) {
                result.append("\n");
            }
            result.append(line);
        }
        return result.toString();
    }

    /**
     * 数据解密
     *
     * @param body
     * @return
     * @throws Exception
     */
    private String decryptData(String body) throws Exception {
        JSONObject resultObject = JSON.parseObject(body);
        JSONObject resource = resultObject.getJSONObject("resource");
        String ciphertext = resource.getString("ciphertext");
        String nonce = resource.getString("nonce");
        String associatedData = resource.getString("associated_data");

        AesUtil aesUtil = new AesUtil(weChatProperties.getApiV3Key().getBytes(StandardCharsets.UTF_8));
        //密文解密
        String plainText = aesUtil.decryptToString(associatedData.getBytes(StandardCharsets.UTF_8),
                nonce.getBytes(StandardCharsets.UTF_8),
                ciphertext);

        return plainText;
    }

    /**
     * 给微信响应
     *
     * @param response
     */
    private void responseToWeixin(HttpServletResponse response) throws Exception {
        response.setStatus(200);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("code", "SUCCESS");
        map.put("message", "SUCCESS");
        response.setHeader("Content-type", ContentType.APPLICATION_JSON.toString());
        response.getOutputStream().write(JSONUtils.toJSONString(map).getBytes(StandardCharsets.UTF_8));
        response.flushBuffer();
    }
}